//
//  utilities.h
//  diylane-api
//
//  Created by Yucheng on 5/15/17.
//  Copyright © 2017 Yucheng. All rights reserved.
//

#ifndef utilities_h
#define utilities_h

#include <stdio.h>
#include <stdlib.h>
#include <boost/date_time.hpp>
#include <vector>
#include <openssl/sha.h>

namespace diylane
{
namespace util
{

struct Autodelete
{
    Autodelete() {}
    virtual ~Autodelete() {}
};

struct AutodeleteMarker
{
    std::vector<Autodelete *> list;
    AutodeleteMarker()
    {
    }
    ~AutodeleteMarker()
    {
        for (size_t i = 0; i < list.size(); i++)
        {
            Autodelete **p = &list[i];
            if (*p)
            {
                delete *p;
                *p = NULL;
            }
        }
    }
    void mark(Autodelete *a)
    {
        list.push_back(a);
    }
};

// STATIC functions
struct S
{

    static std::string hashStringWithSalt(std::string password, std::string salt)
    {
        char encodedPassword[SHA_DIGEST_LENGTH * 2 + 1] = "";
        std::string passwordWithSalt = password + salt;
        SHA_CTX c;
        unsigned char md[SHA_DIGEST_LENGTH];
        SHA1((unsigned char *)passwordWithSalt.c_str(), passwordWithSalt.length(), md);
        for (int i = 0; i < SHA_DIGEST_LENGTH; i++)
        {
            snprintf(encodedPassword + i * 2, 3, "%02x", md[i]);
        }
        encodedPassword[SHA_DIGEST_LENGTH * 2] = 0;
        return encodedPassword;
    }

    static std::string encPassword(std::string password)
    {
        return hashStringWithSalt(password, "salt_@&*(zUi)*jja28kIudKlADkcd_934");
    }

    static uint64_t utcMilliseconds()
    {
        static boost::posix_time::ptime const epoch(boost::gregorian::date(1970, 1, 1));
        return (boost::posix_time::microsec_clock::universal_time() - epoch).total_milliseconds() / 1000;
    }

    static char *trimL(char *s)
    {
        while (*s)
        {
            if (*s != ' ')
            {
                break;
            }
            s++;
        }
        return s;
    }

    static void trimR(char *s)
    {
        size_t n = strlen(s);
        for (int i = (int)n; i >= 0; i--)
        {
            if (s[i] != ' ')
            {
                break;
            }
            s[i] = '\0';
        }
    }
};
}
}

#endif /* utilities_h */
